package com.atguigu.spzx.handler;

import com.atguigu.spzx.exception.BaseException;
import com.atguigu.spzx.model.vo.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.security.auth.login.LoginException;
import java.util.ArrayList;
import java.util.List;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

//   @ExceptionHandler({Exception.class})
//    public Result error(){
//       return Result.error("操作异常");
//   }

    @ExceptionHandler({BaseException.class, LoginException.class})
    public Result loginError(BaseException baseException){
        log.error(baseException.getMessage());
        return Result.error(baseException.getMessage());
    }
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Result loginError(MethodArgumentNotValidException exception){
        log.error(exception.getMessage());
        BindingResult bindingResult = exception.getBindingResult();
        List<String> errList=new ArrayList<>();
        bindingResult.getFieldErrors().forEach(
                item->{
                    errList.add(item.getDefaultMessage());
                }
        );
        String errMessages = StringUtils.join(errList, ",");
        return Result.error(errMessages);
    }
}
